/**
  ******************************************************************************
  * @file    peripheral.h
  * @author  MCU Application Team
  * @Version V1.0.0
  * @Date    2023-12-01
  * @brief   Peripheral Init 
  ******************************************************************************
**/

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "mcu_peripheral.h"
#include "six_step_cmp.h"
#include "six_step_fsm.h"

IWDG_HandleTypeDef 	IwdgHandle;
COMP_HandleTypeDef  OCCompHandle,ZCPCompHandle;
TIM_HandleTypeDef   Tim1Handle,Tim16Handle,Tim17Handle;
ADC_HandleTypeDef	AdcHandle;
DMA_HandleTypeDef 	DMAHandle;

uint16_t AdcData[ADC_ITEM_CNT];



static void OcOutIOInit()
{
	GPIO_InitTypeDef GPIO_InitStruct= {0};
	CMP_IN_OC_CLK_ENABLE(); 
	
	GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;            
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;

	GPIO_InitStruct.Pin = CMP_IN_OC_PIN;
	GPIO_InitStruct.Pull = GPIO_PULLDOWN;                
	HAL_GPIO_Init(CMP_IN_OC_PORT,&GPIO_InitStruct);

}

static void CmpIOInit()
{
	GPIO_InitTypeDef GPIO_InitStruct= {0};
	
	CMP_IN_U_CLK_ENABLE();	
	CMP_IN_V_CLK_ENABLE();  
	CMP_IN_W_CLK_ENABLE(); 

	GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;            
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;


	GPIO_InitStruct.Pull = GPIO_NOPULL;               
	GPIO_InitStruct.Pin = CMP_IN_U_PIN;
	HAL_GPIO_Init(CMP_IN_U_PORT,&GPIO_InitStruct);
	
	GPIO_InitStruct.Pull = GPIO_NOPULL;               
	GPIO_InitStruct.Pin = CMP_IN_V_PIN;
	HAL_GPIO_Init(CMP_IN_V_PORT,&GPIO_InitStruct);

	GPIO_InitStruct.Pull = GPIO_NOPULL;               
	GPIO_InitStruct.Pin = CMP_IN_W_PIN;
	HAL_GPIO_Init(CMP_IN_W_PORT,&GPIO_InitStruct);
}

static void AdcIOInit()
{
	GPIO_InitTypeDef	GPIO_InitStruct;

	/* Enable GPIO clock ****************************************/
	__HAL_RCC_GPIOA_CLK_ENABLE();

	/* ADC Channel GPIO pin configuration */
	GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
	GPIO_InitStruct.Pull = GPIO_NOPULL;
	
	GPIO_InitStruct.Pin = GPIO_PIN_0;//IDC
	HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
	
	GPIO_InitStruct.Pin = GPIO_PIN_2;//Vv
	HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);	
	
	
	GPIO_InitStruct.Pin = GPIO_PIN_4;//Vw
	HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
	
}
static void DebugIOInit()
{
	GPIO_InitTypeDef   GPIO_InitStruct;
		
	//LED_CTRL
	LedCtrl_DO_CLK_ENABLE();
	GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
	GPIO_InitStruct.Pull = GPIO_PULLUP;
	GPIO_InitStruct.Pin = LedCtrl_DO_PIN;
	HAL_GPIO_Init(LedCtrl_DO_PORT, &GPIO_InitStruct);
	HAL_GPIO_WritePin(LedCtrl_DO_PORT,LedCtrl_DO_PIN, GPIO_PIN_SET);
}
static void McuOnIOInit()
{
//	#ifndef MDK_DEBUG
//	#ifndef UART_DEBUG

//	GPIO_InitTypeDef   GPIO_InitStruct={0};
//	
//	McuOn_DO_CLK_ENABLE();
//	
//	//Output Mode
//	GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
//	GPIO_InitStruct.Pull = GPIO_NOPULL;
//	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
//    GPIO_InitStruct.Pin = McuOn_DO_PIN;
//	HAL_GPIO_Init(McuOn_DO_PORT, &GPIO_InitStruct);
//	
//	McuOn_ONN_SET_HIG;
//	#endif
//	#endif
}
static void DirCmdIOInit()
{
//	#ifndef MDK_DEBUG
//	#ifndef UART_DEBUG

//	GPIO_InitTypeDef   GPIO_InitStruct={0};
//	
//	DirCmd_DI_CLK_ENABLE();
//	
//	//Input Mode
//	GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
//	GPIO_InitStruct.Pull = GPIO_PULLUP;
//	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
//	GPIO_InitStruct.Pin = DirCmd_DI_PIN;
//	HAL_GPIO_Init(DirCmd_DI_PORT, &GPIO_InitStruct);
//	#endif
//	#endif
}



static void PwmIOInit()
{
	GPIO_InitTypeDef   GPIO_InitStruct = {0};
	
	GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
	GPIO_InitStruct.Pull = GPIO_PULLDOWN;
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;

	//HIGSIDE
	//U-HO1-PB1-TIM1_CH3N
	U_PHASE_HIGSIDE_CLK_ENABLE();
	GPIO_InitStruct.Pin = U_PHASE_HIGSIDE_PIN;
	GPIO_InitStruct.Alternate = GPIO_AF2_TIM1;
	HAL_GPIO_Init(U_PHASE_HIGSIDE_PORT, &GPIO_InitStruct);

	//V-HO2-PA7-TIM1_CH1N
	V_PHASE_HIGSIDE_CLK_ENABLE();
	GPIO_InitStruct.Alternate = GPIO_AF2_TIM1;
	GPIO_InitStruct.Pin = V_PHASE_HIGSIDE_PIN;
	HAL_GPIO_Init(V_PHASE_HIGSIDE_PORT, &GPIO_InitStruct);

	//W-HO3-PA1-TIM1_CH2N
	W_PHASE_HIGSIDE_CLK_ENABLE();
	GPIO_InitStruct.Pin = W_PHASE_HIGSIDE_PIN;
	GPIO_InitStruct.Alternate = GPIO_AF14_TIM1;
	HAL_GPIO_Init(W_PHASE_HIGSIDE_PORT, &GPIO_InitStruct);
	
	//LOWSIDE
	GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
	GPIO_InitStruct.Pull = GPIO_PULLDOWN;
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
	//LO1-PA10
	V_PHASE_LOWSIDE_CLK_ENABLE();
	GPIO_InitStruct.Pin = V_PHASE_LOWSIDE_PIN;
	HAL_GPIO_Init(V_PHASE_LOWSIDE_PORT, &GPIO_InitStruct);
	//LO2-PA8
	U_PHASE_LOWSIDE_CLK_ENABLE();
	GPIO_InitStruct.Pin = U_PHASE_LOWSIDE_PIN;
	HAL_GPIO_Init(U_PHASE_LOWSIDE_PORT, &GPIO_InitStruct);
	//LO3-PB3
	W_PHASE_LOWSIDE_CLK_ENABLE();
	GPIO_InitStruct.Pin = W_PHASE_LOWSIDE_PIN;
	HAL_GPIO_Init(W_PHASE_LOWSIDE_PORT, &GPIO_InitStruct);
}

void MC_6StepCmp_IOInit(void)
{
	PwmIOInit();
//	DirCmdIOInit();
//	McuOnIOInit();
	DebugIOInit();
	AdcIOInit();
	OcOutIOInit();
	CmpIOInit();
}

/**
  * @brief  Inner-Comparator Initialzing for IDC scan
  * @param  None
  * @retval None
  */
void OCComp_Init(void)  
{
	OCCompHandle.Instance = COMP1;                                          
	OCCompHandle.Init.InputMinus      = COMP_INPUT_MINUS_VCC;
	OCCompHandle.Init.InputPlus       = COMP_INPUT_PLUS_IO1;  //PB8                  
	OCCompHandle.Init.OutputPol       = COMP_OUTPUTPOL_NONINVERTED;                
	OCCompHandle.Init.Mode            = COMP_POWERMODE_HIGHSPEED;              
	OCCompHandle.Init.Hysteresis      = COMP_HYSTERESIS_DISABLE;
	OCCompHandle.Init.WindowMode      = COMP_WINDOWMODE_DISABLE;               
	OCCompHandle.Init.TriggerMode     = COMP_TRIGGERMODE_IT_RISING;
	OCCompHandle.Init.DigitalFilter	= 10;

	__HAL_RCC_COMP1_CLK_ENABLE();
	if (HAL_COMP_Init(&OCCompHandle) != HAL_OK)                             
	{
		Error_Handler();
	} 

	HAL_COMP_Start(&OCCompHandle);                                           

	HAL_NVIC_SetPriority(ADC_COMP_IRQn, BLDC_HOC_COMP_IRQ_PRI, 0);
	HAL_NVIC_EnableIRQ(ADC_COMP_IRQn);
}
/**
  * @brief  Inner-Comparator Initialzing for BEMF-ZCP scan
  * @param  None
  * @retval None
  */
void ZCPComp_Init(void)  
{
	ZCPCompHandle.Instance = COMP2;                                          
	ZCPCompHandle.Init.InputMinus      = COMP_Vo;
	ZCPCompHandle.Init.InputPlus       = COMP_Vu;                    
	ZCPCompHandle.Init.OutputPol       = COMP_OUTPUTPOL_NONINVERTED;                
	ZCPCompHandle.Init.Mode            = COMP_POWERMODE_HIGHSPEED;              
	ZCPCompHandle.Init.Hysteresis      = COMP_HYSTERESIS_ENABLE;//COMP_HYSTERESIS_DISABLE;
	ZCPCompHandle.Init.WindowMode      = COMP_WINDOWMODE_DISABLE;               
	ZCPCompHandle.Init.TriggerMode     = COMP_TRIGGERMODE_NONE;
	ZCPCompHandle.Init.DigitalFilter	= 10;
	
	__HAL_RCC_COMP2_CLK_ENABLE();
	if (HAL_COMP_Init(&ZCPCompHandle) != HAL_OK)                             
	{
		Error_Handler();
	} 

	HAL_COMP_Start(&ZCPCompHandle);                                           
}

static void AdcDmaInit()
{
	//ADC DMA
	__HAL_RCC_SYSCFG_CLK_ENABLE();
	__HAL_RCC_DMA_CLK_ENABLE();
	HAL_SYSCFG_DMA_Req(0);                                      
 
	DMAHandle.Instance                 = DMA1_Channel1;          
	DMAHandle.Init.Direction           = DMA_PERIPH_TO_MEMORY;   
	DMAHandle.Init.PeriphInc           = DMA_PINC_DISABLE;      
	DMAHandle.Init.MemInc              = DMA_MINC_ENABLE;        
	DMAHandle.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD; 
	DMAHandle.Init.MemDataAlignment    = DMA_MDATAALIGN_HALFWORD; 
	DMAHandle.Init.Mode                = DMA_CIRCULAR;            
	DMAHandle.Init.Priority            = DMA_PRIORITY_VERY_HIGH;  

	HAL_DMA_DeInit(&DMAHandle);                                  
	HAL_DMA_Init(&DMAHandle);                                     
	__HAL_LINKDMA(&AdcHandle, DMA_Handle, DMAHandle);                   

	

	DMA1_Channel1->CNDTR = ADC_ITEM_CNT;
	DMA1_Channel1->CPAR = (uint32_t )&(ADC1->DR);
	DMA1_Channel1->CMAR = (uint32_t )AdcData;
	DMA1_Channel1->CCR |= 0x1;

	__HAL_DMA_ENABLE_IT(&DMAHandle,DMA_IT_TC);

	HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, BLDC_ADC_DMA_IRQ_PRI, 0);
	HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);

}


/**
  * @brief  ADC module Initizing
  * @param  None
  * @retval None
  */
void MC_6StepCmp_ADC_Init(void)
{	
	
	__HAL_RCC_ADC_CLK_ENABLE();
	__HAL_RCC_ADC_FORCE_RESET();
	__HAL_RCC_ADC_RELEASE_RESET();

	AdcHandle.Instance         			 =  ADC1;
	AdcHandle.Init.ClockPrescaler        = ADC_CLOCK_SYNC_PCLK_DIV2;         //Max Freq

	AdcHandle.Init.Resolution            = ADC_RESOLUTION_12B;            /* 12-bit resolution for converted data */
	AdcHandle.Init.DataAlign             = ADC_DATAALIGN_RIGHT;           /* Right-alignment for converted data */

	AdcHandle.Init.ScanConvMode          = ADC_SCAN_DIRECTION_FORWARD;//ADC_SCAN_DIRECTION_FORWARD;    /* Sequence disabled (ADC conversion on only 1 channel: channel set on rank 1) */
	AdcHandle.Init.EOCSelection          = ADC_EOC_SEQ_CONV;//ADC_EOC_SINGLE_CONV;           /* EOC flag picked-up to indicate conversion end */
	AdcHandle.Init.LowPowerAutoWait      = ENABLE;                       /* Auto-delayed conversion feature disabled */
	AdcHandle.Init.ContinuousConvMode    = DISABLE;                      /* Continuous mode enabled (automatic conversion restart after each conversion) */
	AdcHandle.Init.DiscontinuousConvMode = DISABLE;//ENABLE;             /* Parameter discarded because sequencer is disabled */
	AdcHandle.Init.ExternalTrigConv      = ADC_EXTERNALTRIGCONV_T1_CC4;            /* Software start to trig the 1st conversion manually, without external event */
	AdcHandle.Init.ExternalTrigConvEdge  =ADC_EXTERNALTRIGCONVEDGE_FALLING; ; /* Parameter discarded because software trigger chosen */

	AdcHandle.Init.DMAContinuousRequests = DISABLE;              		  /* ADC DMA continuous request to match with DMA circular mode */
	AdcHandle.Init.Overrun               = ADC_OVR_DATA_PRESERVED;//ADC_OVR_DATA_OVERWRITTEN;      /* DR register is overwritten with the last conversion result in case of overrun */
	AdcHandle.Init.SamplingTimeCommon    = ADC_SAMPLETIME_7CYCLES_5;//ADC_SAMPLETIME_7CYCLES_5;//ADC_SAMPLETIME_28CYCLES_5;//ADC_SAMPLETIME_13CYCLES_5;//ADC_SAMPLETIME_7CYCLES_5;//ADC_SAMPLETIME_3CYCLES_5;//ADC_SAMPLETIME_5CYCLES_5;//ADC_SAMPLETIME_71CYCLES_5;//ADC_SAMPLETIME_239CYCLES_5;//ADC_SAMPLETIME_239CYCLES_5;
	
	if (HAL_ADC_Init(&AdcHandle) != HAL_OK)
	{
		Error_Handler();
	}
	
	//SPD/NTC/IDC
	SET_BIT (ADC1->CHSELR,IDC_CHANNEL|NTC_CHANNEL|UDC_CHANNEL);
 	ADC1->CFGR1 |= ADC_CFGR1_DMAEN;

	AdcDmaInit();
}




static void TIM16_Init(void)
{
	__HAL_RCC_TIM16_CLK_ENABLE();
	
	//TIM16 - Calculating motor speed
	Tim16Handle.Instance = TIM16;	                                         		
	Tim16Handle.Init.Period            = BLDC_TIM16_CNT_PERIOD;                
	Tim16Handle.Init.Prescaler         = BLDC_TIM16_PSC - 1;														
	Tim16Handle.Init.ClockDivision     = TIM_CLOCKDIVISION_DIV1;           
	Tim16Handle.Init.CounterMode       = TIM_COUNTERMODE_UP;               
	Tim16Handle.Init.RepetitionCounter = 1-1;                              
	Tim16Handle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;   
	if (HAL_TIM_Base_Init(&Tim16Handle) != HAL_OK)                         
	{
		Error_Handler();
	}
	if(HAL_TIM_Base_Start(&Tim16Handle) != HAL_OK)
	{
		/* Starting Error */
		Error_Handler();
	}

}
static void TIM17_Init(void)
{
	__HAL_RCC_TIM17_CLK_ENABLE();

	// TIM17 - Control motor phase change
	Tim17Handle.Instance 				= TIM17;
	Tim17Handle.Init.Period    			= BLDC_TIM17_CNT_PERIOD;                
	Tim17Handle.Init.Prescaler 			= BLDC_TIM17_PSC-1;
	Tim17Handle.Init.ClockDivision     	= TIM_CLOCKDIVISION_DIV1;           
	Tim17Handle.Init.CounterMode       	= TIM_COUNTERMODE_UP;               
	Tim17Handle.Init.RepetitionCounter 	= 1-1;                              
	Tim17Handle.Init.AutoReloadPreload 	= TIM_AUTORELOAD_PRELOAD_DISABLE;   

	if (HAL_TIM_Base_Init(&Tim17Handle) != HAL_OK) 
	{
		Error_Handler();
	}
	if(HAL_TIM_Base_Start(&Tim17Handle) != HAL_OK)
	{
		/* Starting Error */
		Error_Handler();
	}
	HAL_NVIC_SetPriority(TIM17_IRQn, BLDC_PHASE_COMM_IRQ_PRI, 0);
	HAL_NVIC_EnableIRQ(TIM17_IRQn);

}
static void TIM1_Init(void)
{
	TIM_OC_InitTypeDef              	sPWMConfig = {0};

	__HAL_RCC_TIM1_CLK_ENABLE();
	Tim1Handle.State = HAL_TIM_STATE_RESET;
	//TIM1 - Control carrier frequency
	Tim1Handle.Instance = TIM1;                                                      
	Tim1Handle.Init.Period            = BLDC_ROTOR_AUTO_STUDY_PERIOD-1;
	Tim1Handle.Init.Prescaler         = BLDC_TIM1_PSC - 1;                                    		
	Tim1Handle.Init.ClockDivision     = TIM_CLOCKDIVISION_DIV1;                                          
	Tim1Handle.Init.CounterMode       = TIM_COUNTERMODE_UP;                          
	Tim1Handle.Init.RepetitionCounter = 1 - 1;                                       
	Tim1Handle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;              
	if (HAL_TIM_PWM_Init(&Tim1Handle) != HAL_OK)                                     
	{
		Error_Handler();
	}

	sPWMConfig.OCMode       = TIM_OCMODE_PWM1;                                      
	sPWMConfig.OCNPolarity  = TIM_OCNPOLARITY_HIGH;                                
	sPWMConfig.OCNIdleState = TIM_OCNIDLESTATE_RESET; 
	sPWMConfig.OCNPolarity  = TIM_OCNPOLARITY_HIGH;                                
	sPWMConfig.OCNIdleState = TIM_OCNIDLESTATE_RESET; 

	sPWMConfig.OCFastMode   = TIM_OCFAST_DISABLE;                                  


	sPWMConfig.Pulse = 0;                                       
	if (HAL_TIM_PWM_ConfigChannel(&Tim1Handle, &sPWMConfig, TIM_CHANNEL_1) != HAL_OK)
	{
		Error_Handler();
	}

	sPWMConfig.Pulse = 0;                                            
	if (HAL_TIM_PWM_ConfigChannel(&Tim1Handle, &sPWMConfig, TIM_CHANNEL_2) != HAL_OK)
	{
		Error_Handler();
	}

	sPWMConfig.Pulse = 0;                                          
	if (HAL_TIM_PWM_ConfigChannel(&Tim1Handle, &sPWMConfig, TIM_CHANNEL_3) != HAL_OK)
	{
		Error_Handler();
	}

	sPWMConfig.Pulse = 0;                                                
	if (HAL_TIM_PWM_ConfigChannel(&Tim1Handle, &sPWMConfig, TIM_CHANNEL_4) != HAL_OK)
	{
		Error_Handler();
	}

	//Reset the TIM Output compare preload
	__HAL_TIM_DISABLE_OCxPRELOAD(&Tim1Handle,TIM_CHANNEL_1);
	__HAL_TIM_DISABLE_OCxPRELOAD(&Tim1Handle,TIM_CHANNEL_2);
	__HAL_TIM_DISABLE_OCxPRELOAD(&Tim1Handle,TIM_CHANNEL_3);
	__HAL_TIM_DISABLE_OCxPRELOAD(&Tim1Handle,TIM_CHANNEL_4);
	/* Output PWM on Channel 1N */
	if (HAL_TIMEx_PWMN_Start(&Tim1Handle, TIM_CHANNEL_1) != HAL_OK)
	{
		Error_Handler();
	}
	/* Output PWM on Channel 2N */
	if (HAL_TIMEx_PWMN_Start(&Tim1Handle, TIM_CHANNEL_2) != HAL_OK)
	{
		Error_Handler();
	}
	/* Output PWM on Channel 3N */
	if (HAL_TIMEx_PWMN_Start(&Tim1Handle, TIM_CHANNEL_3) != HAL_OK)
	{
		Error_Handler();
	}
	/* Output PWM on Channel 4 */
	if (HAL_TIM_PWM_Start(&Tim1Handle, TIM_CHANNEL_4) != HAL_OK)
	{
		Error_Handler();
	}
	
	__HAL_TIM_ENABLE_IT(&Tim1Handle,TIM_IT_UPDATE);
	
	HAL_NVIC_SetPriority(TIM1_BRK_UP_TRG_COM_IRQn, BLDC_PWMON_IRQ_PRI, 0);
	HAL_NVIC_EnableIRQ(TIM1_BRK_UP_TRG_COM_IRQn);
	
//	__HAL_TIM_ENABLE_IT(&Tim1Handle,TIM_IT_CC4);

//	HAL_NVIC_SetPriority(TIM1_CC_IRQn, BLDC_PWMON_IRQ_PRI, 0);
//	HAL_NVIC_EnableIRQ(TIM1_CC_IRQn);

}
/**
  * @brief  Timers Initializing
  * @param  None
  * @retval None
  */
void MC_6StepCmp_PWM_Init(void)
{
	TIM16_Init();
	TIM17_Init();
	TIM1_Init();
}


void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_LSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;                                                    
  RCC_OscInitStruct.HSIDiv = RCC_HSI_DIV1;                                                   
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_24MHz;                         	
  RCC_OscInitStruct.HSEState = RCC_HSE_OFF;                                                   
  RCC_OscInitStruct.HSEFreq = RCC_HSE_16_32MHz;                                               
  RCC_OscInitStruct.LSIState = RCC_LSI_ON;                                                  
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;                                              
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;                                       

  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)                                      
  {
    Error_Handler();
  }


  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1; 
  
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;                                      		
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;                                          		
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;                                           		

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)                      		
  {
    Error_Handler();
  }

}

void wdg_Init(void)
{
    IwdgHandle.Instance = IWDG;       						  
    IwdgHandle.Init.Prescaler = IWDG_PRESCALER_32;  			
	IwdgHandle.Init.Reload = (1000);                			

    if(HAL_IWDG_Init(&IwdgHandle) != HAL_OK) 			  	
    {
		Error_Handler();
    }

}
void clear_Wdg(void)
{
	if(HAL_IWDG_Refresh(&IwdgHandle) != HAL_OK)
	{
		Error_Handler();
	}
}

void delay_2us(uint32_t delay_us)
{    
  volatile unsigned int num;
  volatile unsigned int t;

  
  for (num = 0; num < delay_us; num++)
  {
    t = 0;
    while (t != 0)
    {
      t--;
    }
  }
}
void delay_ms(uint16_t delay_ms)
{   
	#if WDG_EN
	clear_Wdg();
	#endif

	volatile unsigned int num;
	for (num = 0; num < delay_ms; num++)
	{
		delay_2us(2000);
	}
}

void delay_s(uint16_t delay_s)
{   
	#if WDG_EN
	clear_Wdg();
	#endif

	volatile unsigned int num;
	for (num = 0; num < delay_s; num++)
	{
		delay_ms(500);
		#if WDG_EN
		clear_Wdg();
		#endif
		delay_ms(500);
		#if WDG_EN
		clear_Wdg();
		#endif
	}
}
